package com.szr.leex.dao.converter.type.java;

import org.hibernate.type.descriptor.WrapperOptions;
import org.hibernate.type.descriptor.java.AbstractTypeDescriptor;
import org.hibernate.type.descriptor.java.CharacterTypeDescriptor;

import com.szr.leex.po.enums.GenderEnum;

/**
 * GenderJavaTypeDescriptor
 * Created by WangChen on 2018/9/6 9:57.
 */
public class GenderTypeDescriptor extends AbstractTypeDescriptor<GenderEnum> {

    public static final GenderTypeDescriptor INSTANCE = new GenderTypeDescriptor();

    GenderTypeDescriptor(){
        super(GenderEnum.class);
    }
    protected GenderTypeDescriptor(Class<GenderEnum> type) {
        super(type);
    }


    @Override
    public String toString(GenderEnum value) {
        return value == null ? null : value.name();
    }

    @Override
    public GenderEnum fromString(String string) {
        return string == null ? null : GenderEnum.valueOf( string );
    }

    /**
     * the unwrap method is used when passing the Class<X> type as a PreparedStatement bind parameter
     */
    @Override
    public <X> X unwrap(GenderEnum value, Class<X> type, WrapperOptions wrapperOptions) {
        return CharacterTypeDescriptor.INSTANCE.unwrap(
                value == null ? null : value.getCode(),
                type,
                wrapperOptions
        );
    }

    /**
     *  the wrap method is used to transform the JDBC column value object to the actual mapping object type
     */
    @Override
    public <X> GenderEnum wrap(X value, WrapperOptions wrapperOptions) {
        if (value == null){
            return null;
        }
        char v = CharacterTypeDescriptor.INSTANCE.wrap(value, wrapperOptions);
        return GenderEnum.fromCode(v);
    }
}
